package com.aruba.attendance.database.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.aruba.attendance.database.entity.OverworkDurationEntity
import kotlinx.coroutines.flow.Flow

/**
 * 打卡记录的Dao层
 * Created by aruba on 2023/2/15.
 */
@Dao
interface OverworkDurationDao {
    @Insert
    suspend fun insert(overworkDurationEntity: OverworkDurationEntity)

    // 获取总计时长
    @Query("SELECT sum(duration) FROM OverworkDurationEntity")
    fun findDurationSum(): Flow<Long?>

    @Query("SELECT duration FROM OverworkDurationEntity WHERE year = :year and month = :month and dayOfMonth = :dayOfMonth")
    fun findDurationFlowByDate(
        year: Int,
        month: Int,
        dayOfMonth: Int
    ): Flow<Long?>

    @Query("SELECT * FROM OverworkDurationEntity WHERE year = :year and month = :month and dayOfMonth = :dayOfMonth")
    suspend fun findDurationByDate(year: Int, month: Int, dayOfMonth: Int): OverworkDurationEntity?

    @Update
    suspend fun updateDurationById(overworkDurationEntity: OverworkDurationEntity)

    @Query("DELETE FROM OverworkDurationEntity")
    suspend fun clear()
}

suspend fun OverworkDurationDao.insertOrUpdate(
    year: Int,
    month: Int,
    dayOfMonth: Int,
    duration: Long
) {
    val calcDuration = if (duration < 0) 0 else duration
    findDurationByDate(year, month, dayOfMonth)?.apply {
        this.duration = calcDuration
        updateDurationById(this)
    } ?: insert(
        OverworkDurationEntity(
            year,
            month,
            dayOfMonth,
            calcDuration
        )
    )
}